﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using CWB.Common.Constant;
using CWB.Common.DTO;
using CWB.Common.Logging;
using CWB.Common.Utilities;
using CWB.Web.Configuration;
using CWB.Web.DB;
using CWB.Web.Models;
using CWB.Web.Models.Configuration;
using CWB.Web.MVC.BaseController;
using CWB.Web.MVC.Filters;
using CWB.WebSite.Models;
using CWB.WebSite.Models.Agent;
using System.Linq;

namespace CWB.WebSite.Controllers.Service
{
    public class AgentServiceController : MultiCultureBaseController
    {
        private static readonly ISysLog Log = SysLog.GetLogger(typeof(AgentServiceController));

        public AgentServiceController(LanguageInfo languageInfo)
            : base(languageInfo)
        {
            ControllerPermision = Permission.Private;
        }

        //
        // GET: /AgentService/
        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult SearchAgent(int? page, string searchkey, int? uplinesn, int? position)
        {
            int iPage = Convert.ToInt16(page);
            int iUplineSN = Convert.ToInt16(uplinesn);
            int iPosition = (Convert.ToInt16(position) < 1) ? 1 : (int)(position);

            string sSearchKey = string.Empty;
            if (!string.IsNullOrEmpty(searchkey))
            {
                sSearchKey = searchkey;
            }

            if (sessionData.trading.loginType == LoginType.Agent && iUplineSN == 0)
            {
                iUplineSN = sessionData.trading.sn;
            }

            DbTableAgent o = new DbTableAgent();
            if (iUplineSN != 0)
            {
                DbModuleAgent d = o.getAgentbySn(iUplineSN);
                iPosition = d.Position + 1;
            }

            AgentViewModel datalisting = doSearchAgent(iPage, sSearchKey, iUplineSN, iPosition);
            datalisting.CurrentPosition = iPosition;

            return Json(datalisting, JsonRequestBehavior.DenyGet);
        }

        //
        // GET: /AgentService/
        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult UpdateAgPwd(int sn, string password)
        {
            ResultBase result = updatePassword(sn, password, null);
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        //
        // GET: /AgentService/
        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult UpdatePwd(int sn, string password, string oldpassword)
        {
            ResultBase result = new ResultBase();

            if (string.IsNullOrEmpty(password))
            {
                result.Result = ReturnCode.Failed;
                result.Message = Localization.TranslateMessage(Err.PasswordCannotBeEmpty);
            }
            else if (string.IsNullOrEmpty(oldpassword))
            {
                result.Result = ReturnCode.Failed;
                result.Message = Localization.TranslateMessage(Err.ConfirmPasswordCannotBeEmpth);
            }
            else
            {
                result = updatePassword(sn, password, oldpassword);
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        private ResultBase updatePassword(int sn, string password, string oldpassword)
        {
            ResultBase result = new ResultBase();
            DbTableAgent o = new DbTableAgent();
            ReturnCode updrtn = o.updatePassword(sn, password, oldpassword);
            switch (updrtn)
            {
                case ReturnCode.Success:
                    result.Message = Localization.TranslateMessage(Msg.UpdateAgentSuccess);
                    break;
                case ReturnCode.Failed:
                    result.Message = Localization.TranslateMessage(Err.UpdateDataFailed);
                    break;
                case ReturnCode.OldPwdIncorrect:
                    result.Message = Localization.TranslateMessage(Err.OldPasswordIsIncorrect);
                    break;
                default:
                    result.Message = Localization.TranslateMessage(Err.ReturnCodeOutOfControl);
                    break;
            };
            result.Result = updrtn;
            return result;
        }

        private AgentViewModel doSearchAgent(int page, string searchkey, int parentSN, int position)
        {
            //Create a DB object.
            DbTableAgent odb = new DbTableAgent();
            //Handel Paging.
            Paging pg = new Paging()
            {
                pageSize = AppConfigManager.SystemSetting.UsersPageingSize,
                currentPage = page
            };
            //Handel Sorting
            DBSortingPara dbsp = new DBSortingPara();
            dbsp.AddSortingItem("username", SortingType.ASC);
            dbsp.AddSortingItem("loginid", SortingType.ASC);

            //initial ViewModel.
            AgentViewModel datalisting = new AgentViewModel();
            try
            {
                List<DbModuleAgent> listData = odb.getAgentDbModule(ref pg, searchkey, parentSN, position, dbsp);
                List<AgentListingModel> listModel = listData.Select(x => new AgentListingModel()
                {
                    sn = x.sn,
                    Loginid = x.Loginid,
                    status = new CWB.WebSite.Models.Agent.AgentListingModel.Status() { id = x.Status.ToString(), name = EnumMapping.getStatus(x.Status) },
                    Username = x.Username,
                    CreditLimit = x.CreditLimit,
                    Notes = x.Notes,
                    position = new CWB.WebSite.Models.Agent.AgentListingModel.Position() { id = x.Position.ToString(), name = EnumMapping.getPosition(x.Position) },
                    possess = x.Possess
                }).ToList();

                if (listData.Count > 0)
                {
                    datalisting.Result = ReturnCode.Success;
                    datalisting.listModel = listModel;
                    datalisting.totalPages = pg.maxPage;
                }
                else
                {
                    datalisting.Message = Localization.TrandlateMessage(Msg.ThereAreNoDateFound);
                    datalisting.Result = ReturnCode.SuccessWithNoData;
                }
            }
            catch (Exception ex)
            {
                datalisting.setException(ex, "SearchMA");
            }
            return datalisting;
        }


        private List<AgentProdItem> getAgentProdItemFromUI(int[] supportedProds, int[] supportedProdsPrice)
        {
            List<AgentProdItem> proditems = new List<AgentProdItem>() { };
            if (supportedProds != null)
            {
                for (var i = 0; i < supportedProds.Length; i++)
                {
                    proditems.Add(new AgentProdItem()
                    {
                        prodSN = supportedProds[i],
                        price = supportedProdsPrice[i],
                    });
                }
            }
            return proditems;
        }

        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult CreateAgent(string parentSN, string loginid, string username, string creditlimit, string password, int possess, string notes, int[] supportedProds, int[] supportedProdsPrice)
        {
            ResultBase result = new ResultBase();
            DbTableAgent o = new DbTableAgent();
            decimal _creditlimit = 0;
            int _uplineSN = Convert.ToInt16(parentSN);
            if (!decimal.TryParse(creditlimit, out _creditlimit))
            {
                result.setException(new Exception(Localization.TrandlateMessage(Err.AgentCreditlimitFormatWrong)), "CreateMA");
            }
            else if (string.IsNullOrEmpty(loginid) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                result.setException(new Exception(Localization.TrandlateMessage(Err.AgentInformationOmit)), "CreateMA");
            }
            else if (sessionData.trading.loginType == LoginType.Agent && !o.chkIsInHierarchy(_uplineSN))
            {
                result.setException(new Exception(Localization.TrandlateMessage(Err.AgentParentSNincorrect)), "CreateMA");
            }
            else
            {
                int _possess = possess;
                string _notes = notes;
                string _username = username;
                string _loginid = loginid;
                string _password = password;

                try
                {
                    if (o.LoginIdIsExist(loginid, 1))
                    {
                        result.Message = Localization.TrandlateMessage(Err.AgentLoginIdIsExisting);
                    }
                    else
                    {
                        List<AgentProdItem> proditems = getAgentProdItemFromUI(supportedProds, supportedProdsPrice);
                        int position = o.getPositionOfParent(_uplineSN);
                        if (position > 2)
                        {
                            result.Message = Localization.TranslateMessage(Err.AgentPositionOverLevelLimit);
                        }
                        else
                        {
                            position++;
                            DbModuleAgent dmp = new DbModuleAgent()
                            {
                                Possess = _possess,
                                Position = position,
                                Notes = _notes,
                                Username = _username,
                                Loginid = _loginid,
                                Password = _password,
                                CreditLimit = _creditlimit,
                                ProdItems = proditems,
                                uplinesn = _uplineSN
                            };
                            if (o.createAgent(dmp))
                            {
                                result.Message = Localization.TranslateMessage(Msg.CreateAgentSuccess);
                                result.Result = ReturnCode.Success;
                                Log.Debug("Create Agent success, Login ID : {0}", _loginid);
                            }
                            else
                            {
                                result.Message = Localization.TrandlateMessage(Err.SaveOrCreateDataGoProblem);
                                Log.Debug("Create Agent failed, Login ID : {0}", _loginid);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Exception(ex);
                    result.setException(Err.ReceiveParameterTypeIncorrect, "CreateMA");
                }
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult UpdateMA(string sn, string username, string creditlimit, int possess, string notes, int[] supportedProds, int[] supportedProdsPrice)
        {
            ResultBase result = new ResultBase();
            decimal _creditlimit = 0;
            int _sn = 0;
            int.TryParse(sn, out _sn);
            if (!decimal.TryParse(creditlimit, out _creditlimit))
            {
                result.setException(new Exception(Localization.TrandlateMessage(Err.AgentCreditlimitFormatWrong)), "CreateMA");
            }
            else if (_sn < 1 || string.IsNullOrEmpty(username))
            {
                result.setException(new Exception(Localization.TrandlateMessage(Err.AgentInformationOmit)), "CreateMA");
            }
            else
            {
                try
                {
                    int _possess = possess;
                    string _notes = notes;
                    string _username = username;
                    List<AgentProdItem> proditems = getAgentProdItemFromUI(supportedProds, supportedProdsPrice);
                    DbTableAgent o = new DbTableAgent();
                    DbModuleAgent dmp = new DbModuleAgent()
                    {
                        Possess = _possess,
                        Notes = _notes,
                        Username = _username,
                        CreditLimit = _creditlimit,
                        ProdItems = proditems,
                        sn = _sn
                    };
                    if (o.updateAgent(dmp))
                    {
                        result.Message = Localization.TranslateMessage(Msg.UpdateAgentSuccess);
                        result.Result = ReturnCode.Success;
                        Log.Debug("Create Agent success, Login Username : {0}, sn = {1}", _username, _sn);
                    }
                    else
                    {
                        result.Message = Localization.TrandlateMessage(Err.SaveOrCreateDataGoProblem);
                        Log.Debug("Create Agent failed, Login Username : {0}, sn = {1}", _username, _sn);
                    }
                }
                catch (Exception ex)
                {
                    Log.Exception(ex);
                    result.setException(Err.ReceiveParameterTypeIncorrect, "CreateMA");
                }
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public JsonResult Delete(int sn)
        {
            DbTableAgent o = new DbTableAgent();
            ResultBase result = new ResultBase();
            //check the user is exist.

            switch (o.DeleteAgentuBySn(sn))
            {
                case 1:
                    result.Result = ReturnCode.Success;
                    result.Message = Localization.TrandlateMessage(Msg.DeleteSuccess);
                    break;
                case -1:
                    result.Result = ReturnCode.Failed;
                    result.Message = Localization.TrandlateMessage(Err.DeleteDataFailed);
                    break;
                case -2:
                    result.Result = ReturnCode.Failed;
                    result.Message = Localization.TrandlateMessage(Err.AgentCannotDelDueToDownline);
                    break;
                case -9:
                    result.Result = ReturnCode.Failed;
                    result.Message = Localization.TrandlateMessage(Err.QueryDbGotSynctaxError);
                    break;
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }
    }
}